<template>
    <div class="all">
        <!-- <div style="text-align:center;font-size:28px;font-weight:bold;">{{$route.name}}</div> -->
        <div class="search">
            <el-form ref="form" :model="promoterSearch" :inline="true" size="mini">
                <el-form-item label="推广人：">
                    <el-input v-model="promoterSearch.name" clearable placeholder="请输入推广人"></el-input>
                </el-form-item>
                <!-- <el-form-item label="合作负责人：">
                    <el-input v-model="promoterSearch.principal" clearable placeholder="请输入合作负责人"></el-input>
                </el-form-item>
                <el-form-item label="负责人电话：">
                    <el-input
                        v-model="promoterSearch.principalPhone"
                        clearable
                        placeholder="请输入负责人电话"
                    ></el-input>
                </el-form-item> -->
                <el-form-item>
                    <el-button type="primary" @click="searchClick">查 询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="btn">
            <el-button size="medium" type="primary" @click="add()" v-if="jurisdiction.add_state === 1">添 加</el-button>
            <span v-else></span>
            <el-button type="primary" @click="lookdetails">详情</el-button>
        </div>
        <div class="table">
            <!-- 表格 -->
            <el-table
                :data="promoterTable"
                border
                height="560"
                :style="{width:screenWidth+'px'}"
                :cell-style="cellStyle"
                :header-cell-style="rowClass"
                @selection-change="allSelectionChange"
            >
                <!-- <el-table-column type="selection" width="60px"></el-table-column> -->
                <el-table-column label="序号" width="80px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.id }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="姓名" width="180px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="手机号" width="130px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.phone }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" width="180px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.create_time*1000 | formatDate}} {{scope.row.create_time*1000 | formatDateBehind}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="推广码" width="120px">
                    <template slot-scope="scope">
                        <span>
                            <!-- <img :src="'https://dzylab.dpyun.site'+scope.row.code_url" alt=""> -->
                            <el-button v-if="scope.row.code_url === null || scope.row.code_url === ''" @click="createimg(scope.$index,scope.row)" size="mini">生成推广码</el-button>
                            <!-- <el-popoverpopper-class="d_slcl-t-popover" placement="top" trigger="click" v-model="scope.row.visible">
                                <img :src="'https://dzylab.dpyun.site'+scope.row.code_url" alt="">
                                <img :src="'https://dzylab.dpyun.site'+scope.row.code_url" alt="" slot="reference">
                            </el-popover> -->
                            <div v-else @click="browse(scope.$index, scope.row)">
                                <img :src="'https://dzylab.dpyun.site'+scope.row.code_url" style="width:50px;" alt="活动图片" />
                            </div>
                        </span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="用户" width="100px">
                    <template slot-scope="scope">
                        <span class="db cup" @click="lookUser(scope.$index, scope.row)">查看</span>
                    </template>
                </el-table-column> -->
                <el-table-column label="所属门店" width="100px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.shop_id | filname }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="240px" v-if="jurisdiction.update_state === 1 || jurisdiction.delete_state === 1">
                    <template slot-scope="scope">
                        <el-button
                            v-if="jurisdiction.update_state === 1"
                            size="small"
                            type="primary"
                            @click="edit(scope.$index, scope.row)"
                        >修改</el-button>
                        <el-button
                            v-if="jurisdiction.delete_state === 1"
                            size="small"
                            type="danger"
                            @click="remove(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                @size-change="pageCount"
                @current-change="currentPageCount"
                :current-page="currentPage"
                :page-sizes="[10, 50,100,150, 200]"
                :page-size="currentCount"
                layout="prev, pager, next, jumper, sizes,total"
                :total="pageResultSize"
            ></el-pagination>
        </div>
        <div>
            <!-- 添加对话框 -->
            <el-dialog title="添加" width="500px" :visible.sync="addVisible" center @close="closeAdd">
                <el-form :model="addpromoter" ref="addpromoter" :rules="rules">
                    <el-form-item label="推广人：" prop="name" :label-width="formLabelWidth">
                        <el-input clearable v-model="addpromoter.name" placeholder="请输入推广人"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号：" prop="phone" :label-width="formLabelWidth">
                        <el-input clearable v-model="addpromoter.phone" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                    <el-form-item label="门店：" prop="shop_id" :label-width="formLabelWidth">
                        <el-select v-model="addpromoter.shop_id">
                            <el-option v-for="item in shopname" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button @click="cancelAdd">取 消</el-button>
                    <el-button type="primary" @click="confirmAdd">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 修改对话框 -->
            <el-dialog title="修改" width="500px" :visible.sync="editVisible" center @close="closeEdit">
                <el-form :model="editpromoter" ref="editpromoter" :rules="rules">
                    <el-form-item label="推广人：" prop="promoter" :label-width="formLabelWidth">
                        <el-input clearable v-model="editpromoter.name" placeholder="请输入推广人"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号：" prop="phone" :label-width="formLabelWidth">
                        <el-input clearable v-model="editpromoter.phone" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer">
                    <el-button @click="cancelEdit">取 消</el-button>
                    <el-button type="primary" @click="confirmEdit">确 定</el-button>
                </div>
            </el-dialog>
            <el-dialog center :visible.sync="dialogVisible" width="500px">
                <div style="text-align:center;">
                    <img width="250px" height="auto" :src="dialogImageUrl" alt />
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import "../../../static/scss/page.scss";
import utils from "../../util/request";
import {formatDate } from '../../util/time.js';
var that
export default {
    data() {
        return {
            // 分页
            jurisdiction: null,
            currentPage: 1, //初始页面
            currentCount: 10, //当前页面的数据数量
            pageResultSize: 10, //表格数据总数
            screenWidth: window.innerWidth, //可视宽度
            addVisible: false, //添加对话框
            editVisible: false, //修改对话框
            dialogVisible: false, //放大图片的对话框显示
            dialogImageUrl: "", //放大图片的路径
            formLabelWidth: "100px", //表单label宽度
            promoterSearch: {
                //查询框表单
                name: "", //推广人
                phone: "" //手机号
            },
            addpromoter: {
                //添加对话框表单
                id: "",
                name: "", //推广人
                phone: "", //手机号
                create_time: "",//创建时间
                code_url: "",//推广码地址
                shop_id: ""//门店
            },
            editpromoter: {
                //修改对话框表单
                name: "", //推广人
                phone: "" //手机号
            },
            rules:{
                name:[
                    {required:true,message:"请输入添加的推广人",trigger:"blur"}
                ],
                phone:[
                    {required:true,message:"请输入添加推广人手机号",trigger:"blur"}
                ],
                shop_id:[
                    {required:true,message:"请选择对应的店铺",trigger:"blur"}
                ]
            },
            promoterTable: [
                // {
                //     id: 1,
                //     name: "吉林", //推广人
                //     phone: "J" //手机号
                // },
                // {
                //     id: 2,
                //     name: "深圳", //推广人
                //     phone: "S" //手机号
                // },
                // {
                //     id: 3,
                //     name: "北京", //推广人
                //     phone: "B" //手机号
                // }
            ],
            shopname: null,
        };
    },
    filters:{
        // 门店名称
        filname(id){
            if(that.shopname !== null){
                that.shopname.forEach(item=>{
                    id === item.id ? id = item.name : "";
                })
                return id
            }else{return}
        },
         // 时间
		formatDate(time){
			var date = new Date(time);
			return formatDate(date, 'yyyy-MM-dd');
		},
		formatDateBehind(time){
			var date = new Date(time);
			return formatDate(date, 'hh:mm:ss')
		}
    },
    methods: {
        searchClick() {
            // 查询
            let data = {page:this.currentPage,list_rows:this.currentCount}
            for(var i in this.promoterSearch) this.promoterSearch[i] !== '' ? data[i] = this.promoterSearch[i] : '';
            utils.request("/promoter/list","post",JSON.stringify(data)).then(resp=>{
                console.log(resp)
                let data = resp.data.data.data;
                data.forEach((item)=>{
                    data.visible = false;
                })
                this.promoterTable = data;
                this.pageResultSize = resp.data.data.total;
            })
        },
        add() {
            // 添加券码活动
            this.addVisible = true;
        },

        confirmAdd() {
            // 确认添加
            this.$refs.addpromoter.validate((valid)=>{
                if(valid){       
                    let data = {}
                    for(var i in this.addpromoter) this.addpromoter[i] !== '' ? data[i] = this.addpromoter[i] : '';

                    let timestamp = Date.parse(new Date());
                    data.create_time = String(timestamp/1000)
                    data.code_url = null
                    // console.log(data)
                    utils.request("/promoter/add","post",JSON.stringify(data)).then(resp=>{
                        console.log(resp)
                        data.id = resp.data.data;
                        this.promoterTable.length < this.currentCount ? this.promoterTable.push(data) : '';
                        this.addVisible = false;
                        this.addpromoter.name = ""; //推广人
                        this.addpromoter.phone = ""; //手机号
                        this.addpromoter.shop_id = ""; //手机号
                    })
                }else{this.$message.error("添加信息不能为空")}
            })
        },
        cancelAdd() {
            // 取消添加
            this.addVisible = false;
            this.addpromoter.promoter = ""; //推广人
            this.addpromoter.phone = ""; //手机号
        },
        closeAdd() {
            // 关闭添加对话框
            this.addVisible = false;
            this.addpromoter.promoter = ""; //推广人
            this.addpromoter.phone = ""; //手机号
        },
        download(index, row) {
            // 下载
        },
        edit(index, row) {
            // 修改的触发函数
            this.editVisible = true;
            this.editpromoter.id = row.id; //表ID
            this.editpromoter.name = row.name; //推广人
            this.editpromoter.phone = row.phone; //手机号
            this.editpromoter.index = index; //手机号
            console.log(this.editpromoter)
        },
        confirmEdit() {
            // 确认修改
            this.$refs.editpromoter.validate((valid)=>{
                if(valid){
                    let data = {}
                    for(var i in this.editpromoter) i !== "index" ? data[i] = this.editpromoter[i] : '';
                    console.log(data)
                    utils.request("/promoter/update","post",JSON.stringify(data)).then(resp=>{
                        console.log(resp)
                        let key = this.editpromoter.index;
                        for(var o in data) this.promoterTable[key][o] = data[o];
                        this.editVisible = false;
                        this.editpromoter.promoter = ""; //推广人
                        this.editpromoter.phone = ""; //手机号
                    })       
                }
            })
        },
        cancelEdit() {
            // 取消修改
            this.editVisible = false;
            this.editpromoter.promoter = ""; //推广人
            this.editpromoter.phone = ""; //手机号
        },
        closeEdit() {
            // 关闭修改对话框
            this.editVisible = false;
            this.editpromoter.promoter = ""; //推广人
            this.editpromoter.phone = ""; //手机号
        },
        remove(index, row) {
            // 删除 二级确认
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                utils.request("/promoter/delete","post",JSON.stringify({id:row.id})).then(resp=>{
                    console.log(resp)
                    this.promoterTable.splice(index,1) 
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }) 
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
            
        },
        //   表格居中
        cellStyle: function({ row, column, rowIndex, columnIndex }) {
            return "text-align:center;";
        },
        rowClass: function({ row, rowIndex }) {
            return "text-align:center;";
        },
        allSelectionChange: function(val) {
            // 获取选中的内容
            console.log(val);
        },
        lookUser(index, row){
            // 跳转用户
            this.$router.push({ path: "/spreadUser", query: { row: JSON.stringify(row) } });
        },
        lookdetails(){
            this.$router.push({ path: "/spreaddetails" })
        },
        browse(index, row) {
            console.log(index, row);
            this.dialogImageUrl = 'https://dzylab.dpyun.site'+row.code_url;
            this.dialogVisible = true;
        },
        // 每页数据的数量
        pageCount: function(val) {
            this.currentCount = val;
            this.searchClick()
        },
        // 点击的第几页
        currentPageCount: function(val) {
            this.currentPage = val;
            this.searchClick()
        },
        createimg(index,row){
            // console.log(row)
            utils.request("/qrcode/qrcode","post",JSON.stringify({id: row.id})).then(resp=>{
                // console.log(resp)
                this.promoterTable[index].code_url = resp.data.data
            })
        },
        // 店铺名
        requestshops(){
            utils.request("/shop/list","post",JSON.stringify({page:1,list_rows:999999999})).then(resp=>{
                console.log(resp)
                this.shopname = resp.data.data.data.map(item=>{
                    return{
                        id: item["id"],
                        name: item["name"]
                    }
                })
            })
        }
    },
    created() {
        let Base64 = require("js-base64").Base64;
        let menuarr = JSON.parse(Base64.decode(sessionStorage.getItem("menuarr")))
        for(var i=0;i<menuarr.length;i++){
            // console.log(menuarr[i].link)
            if(menuarr[i].link === this.$route.path){
                this.jurisdiction = menuarr[i]
            }else{}
        }
        this.requestshops()
        this.searchClick()
    },
    beforeCreate(){
        that = this;
    },
};
</script>
